<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace app\admin\api;
use app\admin\model\Message;
use app\admin\model\MessageBox;
use app\common\api\BaseApi;
use app\system\api\UserApi;
use app\index\vendor\UMeng\BoyePushApi;

class MessageApi extends BaseApi{

  /**
   * 添加
   */
  const ADD = "admin/MessageApi/add";
  /**
   * 保存
   */
  const SAVE = "admin/MessageApi/save";
  /**
   * 保存根据ID主键
   */
  const SAVE_BY_ID = "admin/MessageApi/saveByID";
  const SAVE_WITH_BOX = "admin/MessageApi/saveWithBox";

  /**
   * 删除
   */
  const DELETE = "admin/MessageApi/delete";

  /**
   * 查询
   */
  const QUERY = "admin/MessageApi/query";
  /**
   * 分页查询带总量
   */
  const QUERY_WITH_COUNT = "admin/MessageApi/queryWithCount";
  const QUERY_CALL_WITH_COUNT = "admin/MessageApi/queryCallWithCount";
  const QUERY_DETAIL_CALL_WITH_COUNT = "admin/MessageApi/queryDetailCallWithCount";
  /**
   * 查询一条数据
   */
  const GET_INFO = "admin/MessageApi/getInfo";
  const GET_INFO_WITH_BOX = "admin/MessageApi/getInfoWithBox";

	/**
	 * 根据用户ID查询消息 前最新50条
	 */
	const QUERY_BY_UID = "admin/MessageApi/queryByUID";

	/**
	 * 查询所有消息分页
	 */
	const QUERY_MESSAGE = "admin/MessageApi/queryMessage";

	/**
	 * 记录消息
	 */
	const RECORD_MESSAGE = "admin/MessageApi/recordMessage";

	/**
	 * 推送消息
	 */
	const PUSH_MESSAGE = "admin/MessageApi/pushMessage";
	const PUSH_MESSAGE_WITH_TYPE = "admin/MessageApi/pushMessageAndRecordWithType";

	/**
	 * 根据消息ID推送消息
	 */
	const PUSH_MESSAGE_BY_MESSAGE_ID = "admin/MessageApi/pushMessageByMessageID";


	protected function _init(){
		$this->model = new Message();
	}
	//删除2人私信消息
	public function saveWithBox($curr_uid,$rela_uid){
		//删除curr接收到的信息 对curr的显示
		$query  = $this -> model ->query('select group_concat(m.id) as ids from itboye_message m left join itboye_message_box mb on m.id=mb.msg_id where m.dtree_type=6078 and mb.to_id='.$curr_uid.' and m.from_id='.$rela_uid);
		if(false === $query) return $this->apiReturnErr($this->model->getDbError());
		$ids = $query[0]['ids'];
		if($ids){
			$box = new MessageBox();
			$result = $box -> where('msg_id in ('.$ids.')') -> save(['msg_status'=>2]);
			if (false === $result) return $this -> apiReturnErr($box -> getDbError());
		}
    //删除curr发送的信息 对curr的显示
		$query  = $this -> model ->query('select group_concat(m.id) as ids from itboye_message m left join itboye_message_box mb on m.id=mb.msg_id where m.dtree_type=6078 and mb.to_id='.$rela_uid.' and m.from_id='.$curr_uid);
		if(false === $query) return $this->apiReturnErr($this->model->getDbError());
		$ids = $query[0]['ids'];
		if($ids){
			$result = $this -> model -> where('id in ('.$ids.')') -> save(['status'=>-1]);
			if (false === $result) return $this -> apiReturnErr($this->model -> getDbError());
		}
		return $this->apiReturnSuc('删除成功');
	}
	//获取消息 详情
	public function getInfoWithBox($map,$order=false,$field=false){
		$result = $this->model->alias('m')
		->join('left join __MESSAGE_BOX__ as mb on mb.msg_id=m.id')
		->where($map)->order($order)-> field($field) -> find();
		if ($result === false) {
        $error = $this -> model -> getDbError();
        return $this -> apiReturnErr($error);
    } else {
        return $this -> apiReturnSuc($result);
    }
	}

	//私信详情分页
	public function queryDetailCallWithCount($map = null, $page = ['curpage'=>1,'size'=>10],$order = false, $params = false){
		// trace('---map---');
		// trace($map);
		// 未删除的发送信息status=1 和 未删除的接收信息msg_status<>2
		if(!isset($map['curr_uid'])) return $this->apiReturnErr('api:curr uid缺失');
		if(!isset($map['rela_uid'])) return $this->apiReturnErr('api:rela uid缺失');
		$string = " and  dtree_type = 6078";
 	  if(isset($map['start_time'])) $string .= ' and `send_time`>'.$map['start_time'];

 	  $pageno   = intval($page['curpage']);
		$pagesize = intval($page['size']);

		$Model = new \think\Model();
		$count = $Model ->query("select count(uid) as c  from(".
"(select mb.to_id as uid  from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$map['curr_uid']." and mb.`to_id` = ".$map['rela_uid'].$string.
" and m.`status`=1 )union all".
"(select m.`from_id` as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$map['rela_uid']." and mb.`to_id` = ".$map['curr_uid'].$string.
" and mb.`msg_status`<>2)) msg");
		if(false === $count) return $this->apiReturnErr($Model->getDbError());
		$count = intval($count[0]['c']);
		$pages = ceil($count/$pagesize);
		if($pageno<1 || $pageno >$pages) $pageno = max(1,$pages);

		$list  = $Model ->query("select id,content,send_time,from_id,to_id,msg_status from(".
"(select m.*,mb.to_id,mb.msg_status,mb.to_id as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$map['curr_uid']." and mb.`to_id` = ".$map['rela_uid'].$string.
" and m.`status`=1 )union all".
"(select m.*,mb.to_id,mb.msg_status,m.from_id as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$map['rela_uid']." and mb.`to_id` = ".$map['curr_uid'].$string.
" and mb.`msg_status`<>2)) msg order by `send_time` asc limit ".($pageno-1)*intval($pagesize).','.$pagesize);
		if(false === $list) return $this->apiReturnErr($Model->getDbError());
		else return $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
	}
	//用户的私信 - 分页
	public function queryCallWithCount($map = null, $page = ['curpage'=>1,'size'=>10],$order = false, $params = false){
		// $name  = '用户私信';
		//未删除的发送信息status=1 和 未删除的接收信息msg_status<>2
		if(!isset($map['uid'])) return $this->apiReturnErr('api:uid缺失');
		$string = $map['uid'].' and `status`=1 and `msg_status`<>2 and `dtree_type` = 6078';
		if(isset($map['start_time'])) $string .= ' and `send_time`>'.$map['start_time'];

		$pageno   = intval($page['curpage']);
		$pagesize = intval($page['size']);
		if($pageno<1) $pageno = 1;

		$Model = new \think\Model();
		// $count = 
		$count = $Model ->query("select count(*) as c from (select uid from (".
"(select mb.`to_id` as uid  from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$string.
" and m.`status`=1)union all".
"(select m.`from_id` as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where mb.`to_id` = ".$string.
" and mb.`msg_status`<>2)) msg group by uid ) p");
		if(false === $count) return $this->apiReturnErr($Model->getDbError());
		$count = intval($count[0]['c']);
		//只已读最新一条 正好对应
		$list  = $Model ->query("select id,content,send_time,from_id,to_id,msg_status from (select id,content,send_time,from_id,to_id,msg_status,uid from(".
"(select m.*,mb.to_id,mb.msg_status,mb.to_id as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where m.`from_id` = ".$string.
" and m.`status`=1 )union all".
"(select m.*,mb.to_id,mb.msg_status,m.from_id as uid from itboye_message  as m ".
"left join itboye_message_box as mb on m.`id`=mb.`msg_id` ".
// "left join common_datatree as d on d.name='".$name."'".
" where mb.`to_id` = ".$string.
" and mb.`msg_status`<>2)) msg order by `send_time` desc ) p group by uid limit ".($pageno-1)*intval($pagesize).','.$pagesize);
		if(false === $list) return $this->apiReturnErr($Model->getDbError());
		else return $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
	}
	//消息分页
	public function queryWithCount($map = null, $page = ['curpage'=>1,'size'=>10],$order = false, $params = false, $fields = false) {
        $query = $this->model;
        if(!empty($map)){
        	if(isset($map['msg_type'])){
						$msg_type   = intval($map['msg_type']);
						$uid        = intval($map['uid']);
						$start_time = intval($map['start_time']);
        		$name       = "";
						if($msg_type == 1){
							$name = '系统消息';
						}else if($msg_type == 2){
							$name = '订单通知';
						}else if($msg_type == 3){
							$name = '物流通知';
						}else if($msg_type == 4){
							$name = '中奖信息';
						}
						if($name == '') return $this->apiReturnErr("消息类型缺失");
						$map = array(
							// 'to_id'      => array('IN',array($uid,-2)),
							// 'send_time'  => array('GT',$start_time),
							// 'msg_status' => array('NEQ',2),
							'm.status'     => 1,
							'd.name'       => $name
						);
						$map['_string'] = 'mb.to_id in (-2,'.$uid.')';
						if($start_time) $map['_string'] = $map['_string'].' and send_time>'.$start_time;
						$map['_string'] = $map['_string'].' and msg_status<>2';

		        $query = $query ->alias("m")->join(" __MESSAGE_BOX__ as mb on m.id = mb.msg_id")->join("common_datatree as d on m.dtree_type = d.id",'left')->where($map);//->fetchSql(true);
						$order  = 'm.send_time desc';
						$fields = 'm.id,m.content,m.title,m.create_time,m.send_time,m.from_id,mb.to_id,m.summary,mb.msg_status,m.extra';
		        $query = $query ->order($order);
		        $query = $query ->field($fields);
		        $list  = $query ->page($page['curpage'] . ',' . $page['size']) -> select();
		        if (false === $list) {
		            $error = $this -> model -> getDbError();
		            return $this -> apiReturnErr($error);
		        }

		        $count = $this -> model -> alias("m") -> join(" __MESSAGE_BOX__ as mb on m.id = mb.msg_id") -> join("common_datatree as d on m.dtree_type = d.id",'left')->where($map) -> count();
		        return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
        	}else{
        		return $this->apiReturnErr("消息类型缺失");
        	}
        }else{
        	return $this->apiReturnErr("条件缺失");
        }
  }

	public function queryByUID($uid=0,$msg_type=0,$start_time=0){
		if(!is_numeric($uid)) $uid = 0;
		if(!is_numeric($start_time)) $start_time=0;

		$name = "";
		if($msg_type==1){
			$name = '系统消息';
		}else if($msg_type==2){
			$name = '订单通知';
		}else if($msg_type==3){
			$name = '物流通知';
		}
		if($name == '') return $this->apiReturnErr("消息类型缺失");
		$result = apiCall(UserApi::FIND,[['id'=>$uid]]);
		if($result['status']){
			if(empty($result['info'])){
				return array('status'=>true,'info'=>'用户不存在！');
			}
		}else{
			return array('status'=>false,'info'=>$result['info']);
		}

		/*$query = "SELECT a.id,dtree_type,content,title,send_time,from_id,to_id,summary,status,msg_status FROM itboye_message as a,itboye_message_box as b where msg_id=a.id and to_id=$uid and send_time>$start_time order by send_time desc limit 0,50";
		$result = $this->model->query($query);*/

		$map = array(
			'to_id' => array('IN',array($uid,-2)),
			'send_time' => array('GT',$start_time),
			'msg_status' => array('NEQ',2),
			'status'=> 1,
			'name' => $name
		);
		$order = 'send_time desc';
		$field = 'name,msg_id,content,title,create_time,send_time,from_id,to_id,summary,msg_status,extra';
		$result = $this->model->alias("m")->join(" __MESSAGE_BOX__ as mb on m.id = mb.msg_id")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->order($order)
			->field($field)
			->limit(50)
			->select();

		if($result){
			return ['status'=>true,'info'=>$result];
		}else {
			if($result===false){
				return ['status'=>false,'info'=>$this->model->getDbError()];
			}else{
				return ['status'=>true,'info'=>NULL];
			}
		}

	}

	public function queryMessage($map,$page = array('curpage'=>0,'size'=>10),$order = false, $params = false,$field=false){

		$list = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
				->join("common_datatree as mc on m.dtree_type = mc.id",'left')
				->where($map)
				->order($order)
				->field($field)
				-> page($page['curpage'] . ',' . $page['size'])->select();

		$count = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->order($order)
			->field($field)
			-> count();

		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}

		// 查询满足要求的总记录数
		$Page = new Page($count, $page['size']);

		//分页跳转的时候保证查询条件
		if ($params !== false) {
			foreach ($params as $key => $val) {
				$Page -> parameter[$key] = urlencode($val);
			}
		}

		// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page -> show();

		return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

	}

	public function getMessageByID($id){
		$map = array('m.id'=>$id);
		$list = $this->model->alias("m")->join(" __MESSAGE_BOX__ as  mb on m.id = mb.msg_id  ")
			->join("common_datatree as mc on m.dtree_type = mc.id",'left')
			->where($map)
			->field('m.id,dtree_type,title,content,from_id,summary,status,to_id')
			->find();

		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		} else {
			return $this -> apiReturnSuc($list);
		}

	}

	public function recordMessage($entity=['title'=>'','to_id'=>0,'dtree_type'=>0,'content'=>'','from_id'=>0,'summary'=>'','send_time'=>0,'status'=>1,'extra'=>'']){
		if(empty($entity)){
			return $this -> apiReturnErr('entity参数缺失');
		}

		$message = [
			'dtree_type' =>$entity['dtree_type'],
			'title'      =>$entity['title'],
			'content'    =>$entity['content'],
			'send_time'  =>$entity['send_time'],
			'from_id'    =>$entity['from_id'],
			'summary'    =>$entity['summary'],
			'extra'      =>$entity['extra'],
			'create_time'=>NOW_TIME,
			'status'     =>$entity['status']
		];

		$result = $this->add($message);
		if(!$result['status']){
			return $this -> apiReturnErr($result['info']);
		}else{
			$id = $result['info'];
		}

		$message_box = [
			'to_id'      => $entity['to_id'],
			'msg_status' => 0,
			'msg_id'     => $id
		];

		$result = apiCall(MessageBoxApi::ADD,[$message_box]);
		if(!$result['status']){
			return $this -> apiReturnErr($result['info']);
		}else{
			// if($push){
			// 	$r = $this->pushMessageByMessageID($id);
			// 	if(!$r['status']) return $this->apiReturnErr($r['info']);
			// }
			return $this -> apiReturnSuc($id);
		}

	}

	/**
	 * 发送推送消息
	 */
	public function pushMessage($message=['alert'=>0,'ticker'=>' ','title'=>' ','text'=>' '],$uid,$pushAll=false,$record=false,$after_open=false){
		$param = [
			'alert'  => $message['alert'],
			'ticker' => $message['ticker'],
			'title'  => $message['title'],
			'text'   => $message['text' ]
		];
		if($record){
			//记录消息
			$result = apiCall(DatatreeApi::GET_INFO,[['name'=>L('MESSAGE_PUSH')]]);
			if($result['status']){
				$dtree_type = !empty($result['info'])?$result['info']['id']:0;
			}else{
				$dtree_type = 0;
			}

			if($pushAll){
				$to_id = -2;
			}else{
				$to_id = $uid;
			}

			$entity = [
				'title'      =>$param['title'],
				'content'    =>$param['text'],
				'to_id'      =>$to_id,
				'dtree_type' =>$dtree_type,
				'from_id'    =>0,//0:系统
				'summary'    =>'',
				'send_time'  =>time(),
				'status'     =>1
			];
			$result = $this->recordMessage($entity);
			if($result['status']){
				$msg_id = $result['info'];
			}else{
				return $this->apiReturnErr($result['info']);
			}
		}else{
			$msg_id = $after_open['extra']['id'];
		}
		// vendor('BoyePushApi',APP_PATH.'api/vendor/UMeng/','.php');
		$BoyePushApi = new BoyePushApi();
		if($pushAll){
			//添加系统消息参数,after_open 跳转
			$after_open = [
				'type'  => 'go_activity',
				'param' => Message::MESSAGE_SYSTEM_ACTIVITY,
				'extra' => ['id'=>$msg_id]
			];
			$result = $BoyePushApi->sendAll($param,$after_open);
		}else{
			if($after_open){
				$result = $BoyePushApi->send($uid,$param,$after_open);
			}else{
				$result = $BoyePushApi->send($uid,$param);
			}
		}

		if($result['status']){
			return $this->apiReturnSuc('发送成功！');
		}else{
			return $this->apiReturnErr($result['info']);
		}
	}

	/**
	 * 根据消息ID发送推送消息
	 */
	public function pushMessageByMessageID($id){

		//查找消息内容
		$result = $this->getMessageByID($id);
		if($result['status']){
			$message_info = $result['info'];
		}else{
			return $this->apiReturnErr($result['info']);
		}

		//推送消息
		$uid = $message_info['to_id'];
		$pushAll = false;
		if($uid==-2){
			$pushAll = true;
		}
		$message = array(
			'alert'=>$message_info['content'],
			'ticker'=>$message_info['title'],
			'title'=>$message_info['title'],
			'text'=>$message_info['content']
		);

		$result = $this->pushMessage($message,$uid,$pushAll);

		if($result['status']){
			return $this->apiReturnSuc('推送成功!');
		}else{
			return $this->apiReturnErr($result['info']);
		}

	}

	/**
	 * 记录并推送指定消息类型消息
	 */
	public function pushMessageAndRecordWithType($msg_type,$message = ['title'=>' ','content'=>' ','summary'=>' ','extra'=>'','from_id'=>0,'record'=>true],$uid=0,$pushAll=false,$after_open=false){

		$uid = intval($uid);
		if($uid===0 || $pushAll){
			$to_id = -2;
			$pushAll = true;
		}else{
			$pushAll = false;
			$to_id = $uid;
		}
		//记录消息
		$result = apiCall(DatatreeApi::GET_INFO,[['name'=>$msg_type]]);
		if($result['status']){
			$dtree_type = !empty($result['info'])?$result['info']['id']:0;
		}else{
			$dtree_type = 0;
		}
		$record = isset($message['record']) ? $message['record']:true;
		if($record){
			$entity = [
				'title'      => $message['title'],
				'content'    => $message['content'],
				'to_id'      => $to_id,
				'dtree_type' => $dtree_type,
				'from_id'    => isset($message['from_id'])?$message['from_id']:0,//0:系统
				'summary'    => $message['summary'],
				'extra'      => $message['extra'],
				'send_time'  => time(),
				'status'     => 1
			];
			$result = $this->recordMessage($entity);
			if(!$result['status']) return $this->apiReturnErr($result['info']);
			if($msg_type == '系统消息'){
				$after_open['extra']['id'] = $result['info'];
			}
		}
		$msg = [
			'alert'  =>$message['summary'],
			// 'alert'  =>$message['content'],
			'ticker' =>$message['title'],
			'title'  =>$message['title'],
			'text'   =>$message['content']
		];
		// if($msg_type == '私信消息') $msg['alert'] = $message['summary'];
		$result = $this->pushMessage($msg,$to_id,$pushAll,false,$after_open);
		if(!$result['status']) return $this->apiReturnSuc($result['info']);
		return $this->apiReturnSuc('发送成功!');
	}

}
